<?php
/** 
 * php锁机制
 * @link http://www.tpframe.com/
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * @author 510974211@qq.com
 */
namespace tpfcore\lock;
use tpfcore\base\ILock;
/**
*   array @config='"127.0.0.1", 11211';
*/
class MemcacheLock implements ILock
{
    private $memcache=null;
    public function __construct($config=null)
    {
        $this->memcache = $this->memcache==null ? new Memcache():$this->memcache;

        $this->memcache->connect($config);       // 连接memcache
    }

    public function getLock($key, $timeout=self::EXPIRE)
    {     
        $waitime = 20000;

        $totalWaitime = 0;

        $time = $timeout*1000000;

        while ($totalWaitime < $time && false == $this->memcache->add($key, 1, false, $timeout)) 
        {
            usleep($waitime);

            $totalWaitime += $waitime;
        }
        if ($totalWaitime >= $time)

            throw new Exception('can not get lock for waiting '.$timeout.'s.');

    }

    public function releaseLock($key)
    {
        $this->memcache->delete($key);
    }
}